const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config/index')
exports.handleLogin = (req, res) => {
    const { username, password } = req.body

    const sql = `select password,id,username from ev_users where username=?`

    db.query(sql, [username], (err, results) => {
        if (err) return res.cc(err)
        console.log(results);
        if (results.length == 0) return res.cc('用户名或密码错误')
        const hash = results[0].password

        // .compareSync(加密前的密码, 加密后的密码) 方法比较加密前后的密码是否匹配
        const isSame = bcrypt.compareSync(password, hash)

        if (!isSame) return res.cc('用户密码错误')


        const token = jwt.sign({ id: results[0].id, username: results[0].username }, config.secretKey, {
            algorithm: 'HS256',
            expiresIn: '4d'
        })
        console.log(token);
        res.send({
            status: 0,
            message: "登录成功!",
            token: 'Bearer ' + token

        })

    })
}

exports.handleReguser = (req, res) => {
    const { username, password } = req.body

    // if (!username || !password) {
    //     return res.cc('请输入完整的用户名或密码')
    // }

    const sql = `select * from ev_users where username=?`

    db.query(sql, [username], (err, results) => {
        if (err) return res.cc(err)

        if (results.length != 0) return res.cc('用户名已占有')

        const hash = bcrypt.hashSync(password, 10)

        const sql = `insert into ev_users set username=?,password=?`

        db.query(sql, [username, hash], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows != 1) {
                return res.cc('注册失败')
            }
            res.send({
                status: 0,
                message: '注册成功'
            })
        })

    })

}